<?php
/**
 * Created by PhpStorm.
 * Time: 17:07
 */

namespace common\models\info;
use backend\component\ResultEasyUIFormat;
use common\component\BaseActiveRecord;
use common\component\Constant;
use common\utils\CommonUtil;
use common\component\ResultFormat;
use yii\behaviors\TimestampBehavior;
class Comment extends BaseActiveRecord
{
    const TYPE_COMMENT= 0;  // 0,1,2  留言，文章留言  照片留言
    const TYPE_ARTICLE =1;  //文章留言
    const TYPE_PHOTO = 2;   //照片留言

    static $typeArrayList = [
        self::TYPE_COMMENT => '留言',
        self::TYPE_ARTICLE => '文章留言',
        self::TYPE_PHOTO => '照片留言',
    ];
    public static function tableName()
    {
        return "{{%zt_comment}}";
    }

    public function rules()
    {
        return [
            [['comment_total', 'article_id','view_total','like_total','updated_at', 'created_at',"type",'reply_id',"target_id","updated_at","is_author"],"integer"],
            [['website','nick_name','content'], 'string'],
            ['content','required','message'=>'评论内容不能为空'],
            [['content'],'string','max' => 255],
            ['nick_name','required','message'=>'昵称不能为空'],
        ];
    }

    public function attributes()
    {
        return [
            'id',
            'nick_name',//昵称
            'website',//网站
            'target_id', //回复人的id
            'reply_id',
            'is_author',
            'article_id',
            'content',
            'like_total',
            'comment_total',
            'view_total',
            'type', //0:留言 1：文章 2、相册
            'updated_at',
            'created_at',
        ];
    }

    public function attributeLabels()
    {
        return [
            'id'=>'序列',
            'nick_name'=>'昵称',
            'website'=>'网站',
            'is_author'=>'是否是作者',
            'reply_id'=>'在某条评论下进行讨论',
            'content'=>'内容',
            'type'=>'类型', //0,1,2  留言，文章留言  照片留言
            'updated_at' => '更新时间',
            'created_at' => '创建时间',
            'like_total' => '赞同量',
            'comment_total' => '评论数',
            'view_total' => '浏览量',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_at','updated_at'],
                    self::EVENT_BEFORE_UPDATE => 'updated_at'
                ]
            ]
        ];
    }

    public function updateAttributes($attributes)
    {
        $attributes['updated_at'] = time();
        return parent::updateAttributes($attributes);
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)){
            return false;
        }
        return true;
    }

    public function afterSave($insert, $changedAttributes)
    {
    }


    public function afterFind()
    {
        parent::afterFind();
        $this->opUi();
    }

    public function opUi() {
        $this->ui["target_type"] = self::$typeArrayList[$this->type];
        $this->ui["created_at"] = date("Y-m-d H:i:s",$this->created_at);
    }
    /**
     * 实例化模型对像
     * @param $id
     * @return BaseActiveRecord|null|static
     */
    public static function modelById($id) {
        if (!$id) {
            $model = new self();
        }
        else {
            $model = static::findOne($id);
        }
        return $model;
    }
    /**
     *  获取文章评论 分页
     * @param $article_id
     * @param $page
     * @param $pageSize
     * @return array
     */
    public static function getDataByArtPage($article_id,$page,$pageSize) {
        $q = static::find()->where(["target_id"=>0,"article_id"=>(int)$article_id,"type"=>self::TYPE_ARTICLE])
            ->orderBy("created_at DESC");
        $data = self::arrListByPage($q,$page,$pageSize);
        if (count($data["rows"])) {
            foreach ($data["rows"] as $k => $v) {
                $data["rows"][$k]["created_at"] = date("Y-m-d H:i",$v["created_at"]);
                $data['rows'][$k]['comment_content'] = self::getDialogList($v['id'],$article_id)['rows'];
            }
        }
        return $data;
    }
    /**
     *  获取留言列表
     * @param $article_id
     * @param $page
     * @param $pageSize
     * @return array
     */
    public static function getDataByMessage($page,$pageSize) {
        $q = static::find()->where(["target_id"=>0,"type"=>self::TYPE_COMMENT])
            ->orderBy("created_at DESC");
        $data = self::arrListByPage($q,$page,$pageSize);
        if (count($data["rows"])) {
            foreach ($data["rows"] as $k => $v) {
                $data["rows"][$k]["created_at"] = date("Y-m-d H:i",$v["created_at"]);
                $data['rows'][$k]['comment_content'] = self::getDialogMessageList($v['id'])['rows'];
            }
        }
        return $data;
    }
    public  static function getDialogMessageList($comment_id,$page=1,$pageSize=10){
        $q = static::find()
            ->andWhere(["reply_id"=>$comment_id,"type"=>self::TYPE_COMMENT])
            ->orderBy("created_at DESC");
        $data = self::arrListByPage($q,$page,$pageSize);
        if (count($data["rows"])) {
            foreach ($data["rows"] as $k => $v) {
                $data["rows"][$k]["created_at"] = date("Y-m-d H:i",$v["created_at"]);
                $data["rows"][$k]["reply_name"] = self::getCommentByTargetId($v['target_id'],$v['reply_id'],0,0);
            }
        }
        return $data;
         }


    public static function getNewData(){
        $result = static::find()->orderBy( 'id desc')->asArray()->limit(1)->one();
        $result["reply_name"] = self::getCommentByTargetId($result['target_id'],$result['reply_id'],$result['article_id'],1);
        $result["created_at"] = date("Y-m-d H:i",$result["created_at"]);
        return $result;
    }

    /**
     * 获取用户对话
     * @param $comment_id
     * @param $article_id
     * @param $page
     * @param $pageSize
     * @return array
     */
    public static function getDialogList($comment_id,$article_id,$page=1,$pageSize=10) {
        $q = static::find()
            ->andWhere(["reply_id"=>$comment_id,"article_id"=>$article_id,"type"=>self::TYPE_ARTICLE])
            ->orderBy("created_at DESC");
        $data = self::arrListByPage($q,$page,$pageSize);
        if (count($data["rows"])) {
            foreach ($data["rows"] as $k => $v) {
                $data["rows"][$k]["reply_name"] = self::getCommentByTargetId($v['target_id'],$comment_id,$article_id,0);
            }
        }
        return $data;
    }
   public static function getCommentByTargetId($target_id,$comment_id,$article_id,$type){
       $model = static::find()->where(['id'=>$target_id,"reply_id"=>$comment_id,"article_id"=>$article_id,'type'=>$type])->one();
       if ($model){
           return $model['nick_name'];
       }
   }
    /**
     * 点赞评论
     * @param $comment_id
     * @param $user_id
     * @return mixed
     */
    public static function likeComment($comment_id,$user_id) {
        $model = static::find()->where(['_id'=>new ObjectId($comment_id)])->one();
        if (!$model || $model->status == Comment::STATUS_DELETE) {
            return $model->status == Comment::STATUS_DELETE?['flag'=>false,'data'=>'该评论已删除']:['flag'=>false,'data'=>''];
        }
        $obj = new CommentLikeRedisImp($comment_id);
        $obj->on(CommentLikeRedisImp::EVENT_AFTER_LIKE,["common\component\Messager","like"]);
        if (!$obj->up($user_id)) {
            return ['flag'=>false,'data'=>''];
        }
        $like_count = (int)$model->like_count;
        if (!$model->updateCounters(["like_count"=>1])){
            return ['flag'=>false,'data'=>''];
        }
        $obj->trigger(CommentLikeRedisImp::EVENT_AFTER_LIKE,new NotifyEvent([
            'target_id'=> $comment_id,
            'target_type'=> $model->target_type == self::TYPE_ARTICLE ? "comment":"reply",
            'action' => 'like',
            'sender_id'=> $user_id,
            'content'=>'',
        ]));
        return ['flag'=>true,'data'=>++$like_count];
    }

    /**
     * 取消赞
     * @param $comment_id
     * @param $user_id
     * @return mixed
     */
    public static function cancelikeComment($comment_id,$user_id) {
        $model = static::find()->where(['_id'=>new ObjectId($comment_id)])->one();
        if (!$model) {
            return false;
        }
        $obj = new CommentLikeRedisImp($comment_id);
        if (!$obj->down($user_id)) {
            return false;
        }
        $like_count = (int)$model->like_count;
        //喜欢人数<=0直接返回0;
        if ($like_count  <= 0) {
            return 0;
        }
        if (!$model->updateCounters(["like_count"=>-1])){
            return false;
        }
        return --$like_count;
    }


    public static function dislikeComment($comment_id,$user_id) {
        $model = static::find()->where(['_id'=>new ObjectId($comment_id)])->one();
        if (!$model || $model->status == Comment::STATUS_DELETE) {
            return $model->status == Comment::STATUS_DELETE?["flag"=>false,'data'=>'该评论已删除']:["flag"=>false,'data'=>''];
        }
        $obj = new CommentDislikeRedisImp($comment_id);
        $obj->on(CommentLikeRedisImp::EVENT_AFTER_DISLIKE,["common\component\Messager","like"]);
        if (!$obj->up($user_id)) {
            return ["flag"=>false,'data'=>''];
        }
        $dislike_count = (int)$model->dislike_count;
        if (!$model->updateCounters(["dislike_count"=>1])) {
            return ["flag"=>false,'data'=>''];
        }
        $obj->trigger(CommentLikeRedisImp::EVENT_AFTER_DISLIKE,new NotifyEvent([
            'target_id'=> $comment_id,
            'target_type'=> $model->target_type == self::TYPE_ARTICLE ? "comment":"reply",
            'action' => 'dislike',
            'sender_id'=> $user_id,
            'content'=>'',
        ]));
        return ["flag"=>true,'data'=>++$dislike_count];
    }

    /**
     * 取消踩
     * @param $comment_id
     * @param $user_id
     * @return mixed
     */
    public static function cancelDislikeComment($comment_id,$user_id) {
        $model = static::find()->where(['_id'=>new ObjectId($comment_id)])->one();
        if (!$model) {
            return false;
        }
        $obj = new CommentDislikeRedisImp($comment_id);
        if (!$obj->down($user_id)) {
            return false;
        }
        $dislike_count = (int)$model->dislike_count;
        if (!$model->updateCounters(["dislike_count"=>-1])){
            return false;
        }
        return --$dislike_count;
    }

    /**
     *  加载指定评论的讨论列表
     * @param $comment_id
     * @param $page
     * @param $pageSize
     * @return array
     */
    public static function getDiscussList($comment_id,$page,$pageSize) {
        $q = static::find()->where(["target_id"=>$comment_id])
            ->andWhere(['in','target_type',[self::TYPE_COMMENT,self::TYPE_DIALOG]])
            ->andWhere(['in','status',[self::STATUS_ENABLE,self::STATUS_DELETE]])
            ->orderBy("created_at DESC");
        $data = self::arrListByPage($q,$page,$pageSize);
        return $data;
    }


    /**
     * 列表页数据加载
     */
    public function generateListData($post) {
        //请求参数组装
        $where = [];

        $query = self::find()->where($where);
        $dataArr = self::table($query,$post);
        return $dataArr;

    }

    /**
     * 获取用户的留言记录
     * @param $user_id
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public static function getListByUid($user_id,$page=1,$pageSize=20) {
        //$key = "comment:user:".$user_id.":page:".$page;
        //$data = false;//CommonUtil::getCache(__CLASS__,$key);
        //if (!$data) {
            $q = static::find()->where(['target_id=0',"status"=>self::TYPE_COMMENT])->orderBy("created_at DESC");
            $data = self::arrListByPage($q,$page,$pageSize);
            if (count($data["rows"])) {
                foreach ($data["rows"] as $k=>$v) {
                    $data["rows"][$k]["id"] = (string)$v["_id"];
                    unset($data["rows"][$k]["_id"]);
                    $data["rows"][$k]["format"] = (new BuildComment($v,$user_id))->run();
                    if (isset($data["rows"][$k]["format"]['event'])&&$data["rows"][$k]["format"]['event']) {
                        preg_match("/\/article-(([1-9][0-9]*){1,10})/",$data["rows"][$k]["format"]['event'],$res);
                        if (isset($res[1])) {
                            $url = CommonUtil::generateUrl($res[1],Constant::ROUTE_ARTICLE);
                            $data["rows"][$k]["format"]['event'] = preg_replace("/\/article-(([1-9][0-9]*){1,10})/",$url,$data["rows"][$k]["format"]['event']);
                        }
                    }
                }
                //CommonUtil::setCache(__CLASS__,$key,$data,120);
            }
        //}
        return $data;
    }

    /**
     * 回复评论
     * @param $user_id
     * @param int $page
     * @param int $pageSize
     * @param bool $flag
     * @return array
     */
    public static function getListByUidReply($user_id,$page=1,$pageSize=20,$flag=false) {
        #获取用户评论
        $comment_arr = self::getUserCommentAll($user_id);
        $where = ['and'];
        $id_arr = [''];
        if (count($comment_arr)) {
            foreach ($comment_arr as $key => $article) {
                $comment_arr[$article['id']] = $article;
                $id_arr[] = strval($article['id']);
                unset($comment_arr[$key]);
            }
        }
        $where[] = ['=','status',self::STATUS_ENABLE];
        $where[] = ['in','target_id',$id_arr];
        $where[] = ['=','target_type',self::TYPE_COMMENT];
        $q = static::find()
            ->select(['target_id','user_id','target_type','content','created_at'])
            ->andWhere(['user_id'=>$user_id,'status'=>self::STATUS_ENABLE,'target_type'=>self::TYPE_COMMENT])
            ->orWhere($where)
            ->orderBy("created_at DESC");
        $data = self::arrListByPage($q,$page,$pageSize);
        if (count($data["rows"])) {
            foreach ($data["rows"] as $k=>$v) {
                unset($data['rows'][$k]['_id']);
                $data['rows'][$k]['comment'] = isset($comment_arr[$v['target_id']])?$comment_arr[$v['target_id']]['content']:self::getFieldById($v['target_id'],'content');
                $data['rows'][$k]['is_self_comment'] = in_array($v['target_id'],$id_arr)&&$v['user_id']==$user_id?1:0;   //是否是自己的评论(别人评论自己的评论)
            }
        }
        return $flag?ResultFormat::success("获取成功",$data):$data;
    }

    /**
     * 我评论的文章
     * @param $user_id
     * @param int $page
     * @param int $pageSize
     * @param bool $flag
     * @return array
     */
    public static function getListByUidComment($user_id,$page=1,$pageSize=20,$flag=false) {
        $key = "comment:list:user:".$user_id."page".$page."size:".$pageSize;
//        $data = CommonUtil::getCache(__CLASS__,$key);
//        if (!$data) {
            $q = static::find()
                ->andWhere(['user_id'=>$user_id,'status'=>self::STATUS_ENABLE,'target_type'=>self::TYPE_ARTICLE])
                ->orderBy("created_at DESC");
            $data = self::arrListByPage($q,$page,$pageSize);
            if (count($data["rows"])) {
                foreach ($data["rows"] as $k=>$v) {
                    $data['rows'][$k]['id'] = (string)$v['_id'];
                    unset($data['rows'][$k]['_id']);
                    $data['rows'][$k]['title'] = Article::getFieldById($v['target_id'],'title');
                    $data['rows'][$k]['url'] = CommonUtil::generateUrl($v['target_id'],Constant::ROUTE_ARTICLE);
                }
//                CommonUtil::setCache(__CLASS__,$key,$data,60);
            }
//        }
        return $flag?ResultFormat::success("获取成功",$data):$data;
    }

    /**
     * 获取用户的文章评论
     * @param $user_id
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public static function getUserCommentListByMobile($user_id,$page=1,$pageSize=20) {
        $q = static::find()->where(["user_id"=>$user_id,"status"=>self::STATUS_ENABLE])->andWhere(["in","target_type",[self::TYPE_ARTICLE,self::TYPE_COMMENT]])->orderBy("created_at DESC");
        $data = self::arrListByPage($q,$page,$pageSize);
        if (count($data["rows"])) {
            foreach ($data["rows"] as $k=>$v) {
                unset($data["rows"][$k]);
                $data["rows"][$k]["target_type"] = $v["target_type"];
                $data["rows"][$k]['id'] = (string)$v['_id'];

                if ($v["target_type"] == self::TYPE_ARTICLE) {
                    $author_id = Article::getFieldById($v['target_id'],"author_id");
                    $data["rows"][$k]["articleInfo"] = [
                        "subject" => Article::getFieldById($v['target_id'],"title"),
                        "image"  => Article::getCoverImage($v['target_id']),
                        "linkUrl" => CommonUtil::generateUrl($v['target_id'],Constant::ROUTE_ARTICLE),
                        "created_at" => CommonUtil::formatTime(Article::getFieldById($v['target_id'],"created_at")),
                        "userInfo" => [
                            "id" => $author_id,
                            "alias" => User::getFieldById($author_id,"alias"),
                            "linkUrl" => CommonUtil::generateUrl($author_id,Constant::ROUTE_USER)
                        ]
                    ];
                    $data["rows"][$k]["commentInfo"] = [
                        "alias" => User::getFieldById($user_id,"alias"),
                        "created_at" => CommonUtil::formatTime($v["created_at"]),
                        "content" => $v["content"],
                        "like_count" => $v["like_count"],
                        "dislike_count" => $v["dislike_count"],
                        "comment_count" => $v["comment_count"]
                    ];
                } else {
                    $data["rows"][$k]["replyInfo"] = [
                        "alias" => User::getFieldById($user_id,"alias"),
                        "content" =>$v["content"],
                        "like_count" => $v["like_count"],
                        "dislike_count" => $v["dislike_count"],
                        "comment_count" => $v["comment_count"],
                        "created_at" => CommonUtil::formatTime($v['created_at']),
                    ];
                    $replyComment = Comment::loadRowData($v["target_id"]);
                    $userInfo = User::getCacheUser($replyComment["user_id"]);
                    $data["rows"][$k]["commentInfo"] = [
                        "content" => $replyComment["content"],
                        "created_at" => CommonUtil::formatTime($replyComment['created_at']),
                        "userInfo" => [
                            "id" => $replyComment["user_id"],
                            "face" => isset($userInfo["image"]) ? $userInfo["image"]->imgSrc("120x120"): "",
                            "alias" => User::getFieldById($replyComment["user_id"],"alias"),
                            "linkUrl" => CommonUtil::generateUrl($replyComment["user_id"],Constant::ROUTE_USER)
                        ]
                    ];
                }

            }
        }
        return $data;
    }

    /**
     * 获取用户的回复评论(frontend)
     * @param $user_id
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public static function getUserCommentListFrontend($user_id,$page=1,$pageSize=20) {
        $key = "comment:frontend:user:".$user_id."page:".$page."size:".$pageSize;
//        $data = CommonUtil::getCache(__CLASS__,$key);
//        if (!$data) {
            $q = static::find()->where(["user_id"=>$user_id,"status"=>self::STATUS_ENABLE])->andWhere(["=","target_type",self::TYPE_COMMENT])->orderBy("created_at DESC");
            $data = self::arrListByPage($q,$page,$pageSize);
            if (count($data["rows"])) {
                foreach ($data["rows"] as $k=>$v) {
                    unset($data["rows"][$k]);
                    $data["rows"][$k]["target_type"] = $v["target_type"];
                    $data["rows"][$k]['id'] = (string)$v['_id'];

                    $data["rows"][$k]["replyInfo"] = [
                        "alias" => User::getFieldById($user_id,"alias"),
                        "content" =>$v["content"],
                        "like_count" => $v["like_count"],
                        "dislike_count" => $v["dislike_count"],
                        "comment_count" => $v["comment_count"],
                        "created_at" => CommonUtil::formatTime($v['created_at']),
                    ];
                    $replyComment = Comment::loadRowData($v["target_id"]);
                    $data["rows"][$k]["commentInfo"] = [
                        "content" => $replyComment["content"],
                        "created_at" => CommonUtil::formatTime($replyComment['created_at']),
                        "userInfo" => [
                            "id" => $replyComment["user_id"],
                            "alias" => User::getFieldById($replyComment["user_id"],"alias"),
                            "linkUrl" => CommonUtil::generateUrl($replyComment["user_id"],Constant::ROUTE_USER),
                            "face" => User::getUserFace($replyComment['user_id']),
                        ]
                    ];
                }
//                CommonUtil::setCache(__CLASS__,$key,$data,60);
            }
//        }

        return $data;
    }

    /**
     * 获取用户的文章评论
     * @param $user_id
     * @param int $page
     * @param int $pageSize
     * @return array|mixed
     */
    public static function getUserCommentList($user_id,$page=1,$pageSize=20) {
        $key = "comment:user:".$user_id.":page:".$page;
        $data = CommonUtil::getCache(__CLASS__,$key);
        if (!$data) {
            $q = static::find()->where(["user_id"=>$user_id,"target_type"=>self::TYPE_ARTICLE,"status"=>self::STATUS_ENABLE])->orderBy("created_at DESC");
            $data = self::arrListByPage($q,$page,$pageSize);
            if (count($data["rows"])) {
                foreach ($data["rows"] as $k=>$v) {
                    $tempData = $v;
                    unset($data["rows"][$k]);
                    $author_id = Article::getFieldById($tempData['target_id'],"author_id");
                    $user  = User::getCacheUser($author_id);
                    $data['rows'][$k]["face"] = $user ? ($user['image']?$user['image']->imgSrc("32x32"):"") :"";
                    $data["rows"][$k]["title"] = Article::getFieldById($tempData['target_id'],"title");
                    $data["rows"][$k]["link"] = CommonUtil::generateUrl($tempData["target_id"],Constant::ROUTE_ARTICLE);
                    $data["rows"][$k]["link_front"] = CommonUtil::generateUrl($tempData["target_id"],Constant::ROUTE_ARTICLE);
                    $data["rows"][$k]["user_link"] = $author_id?CommonUtil::generateUrl($author_id,Constant::ROUTE_USER):"";
                    $data["rows"][$k]["content"] = $tempData["content"];
                    $data["rows"][$k]["created_at"] = date("Y-m-d H:i",$tempData["created_at"]);
                }
                CommonUtil::setCache(__CLASS__,$key,$data,600);
            }
        }
        return $data;
    }

    /**
     * 获取用户的文章评论点赞(实际数据)
     * @param $user_id
     * @param $action
     * @param int $page
     * @param int $pageSize
     * @param bool $flag
     * @return array|mixed
     */
    public static function getUserCommentLikeList($user_id,$action,$page=1,$pageSize=20,$flag) {
        $key = "comment:like:user:".$user_id.":page:".$page;
        $data = CommonUtil::getCache(__CLASS__,$key);
        if (!$data) {
            $comment_arr  = static::find()
                ->select(['_id','content'])
                ->where(["user_id"=>$user_id,"target_type"=>self::TYPE_ARTICLE,"status"=>self::STATUS_ENABLE])
                ->asArray()
                ->all();
            if (count($comment_arr)) {
                foreach ($comment_arr as $key => $comment) {
                    $comment_arr[(string)$comment['_id']] = $comment['content'];
                    unset($comment_arr[$key]);
                }
                $where = ['and'];
                $where[] = ['=','action',$action];
                $where[] = ['in','target',array_keys($comment_arr)];
                $q = Notify::find()->where($where)->orderBy('created_at desc');
                $data = self::arrListByPage($q,$page,$pageSize);
                if (count($data["rows"])) {
                    foreach ($data["rows"] as $k=>$v) {
                        $tempData = $v;
                        unset($data["rows"][$k]);
                        $data['rows'][$k]['id'] = (string)$tempData['_id'];
                        $user  = User::getCacheUser($tempData['sender']);
                        $data['rows'][$k]["face"] = $user ? ($user['image']?$user['image']->imgSrc("32x32"):"") :"";
                        $data['rows'][$k]['name'] = $user ? $user->alias : "";
                        $data["rows"][$k]["url"] = CommonUtil::generateUrl($tempData["sender"],Constant::ROUTE_USER);
                        $data["rows"][$k]["content"] = $comment_arr[$tempData['target']];
                        $data["rows"][$k]["reply"] = $tempData['content'];
                        $data["rows"][$k]["created_at"] = date("Y-m-d H:i",$tempData["created_at"]);
                    }
                    CommonUtil::setCache(__CLASS__,$key,$data,120);
                }
            }
        }
        return $flag?ResultFormat::success("success",$data):$data;
    }

    /**
     * @param $user_id
     * @param $action
     * @return int
     */
    public static function getUserCommentLikeTotal($user_id,$action) {
        $total = 0;
        $comment_arr  = static::find()
            ->select(['_id','content'])
            ->where(["user_id"=>$user_id,"target_type"=>self::TYPE_ARTICLE,"status"=>self::STATUS_ENABLE])
            ->asArray()
            ->all();
        if (count($comment_arr)) {
            foreach ($comment_arr as $key => $comment) {
                $comment_arr[(string)$comment['_id']] = $comment['content'];
                unset($comment_arr[$key]);
            }
            $where = ['and'];
            $where[] = ['=','action',$action];
            $where[] = ['in','target',array_keys($comment_arr)];
            $total = Notify::find()->where($where)->count();
        }
        return $total;
    }

    /**
     * 获取用户的文章评论(所有)
     * @param $user_id
     * @return array|mixed
     */
    public static function getUserCommentAll($user_id) {
        $key = "comment:all:user:".$user_id;
        $data = CommonUtil::getCache(__CLASS__,$key);
        if (!$data) {
            $data = static::find()
                    ->select(['_id','content'])
                    ->where(["user_id"=>$user_id,"target_type"=>self::TYPE_ARTICLE,"status"=>self::STATUS_ENABLE])
                    ->orderBy("created_at DESC")
                    ->asArray()
                    ->all();
            if (count($data)) {
                foreach ($data as $key => $val) {
                    $data[$key]['id'] = (string)$val['_id'];
                    $data[$key]['content'] = $val['content'];
                    unset($data[$key]['_id']);
                }
                CommonUtil::setCache(__CLASS__,$key,$data);
            }
        }
        return $data;
    }


    public static function getFieldById($comment_id,$field="like_count") {
        $data = self::loadRowData($comment_id);
        return isset($data[$field]) ? $data[$field] : "";
    }


    public static function loadRowData($comment_id) {
        //$key = "comment:id:".$comment_id;
        //$data = CommonUtil::getCache(__CLASS__,$key);
        //if (!$data) {
            $data = static::find()->where(["_id"=>new ObjectId($comment_id)])->one();
            //if ($data) {
            //    $data["_id"] = (string)$data["_id"];
               // CommonUtil::setCache(__CLASS__,$key,$data);
            //}
        //}
        return $data;
    }

    /**
     * 删除用户自己的评论
     * @param $id
     * @param $user_id
     * @return int
     * @todo 目前只修改评论状态为-1（不显示）需要加到脚本分析删除（没有子回复的物理删除）
     */
    public static function rmSelfComment($id,$user_id) {
        $model = static::findOne(["_id"=>new ObjectId($id),"user_id"=>$user_id]);
        if (!$model) {
            return false;
        }
        $model->status = self::STATUS_DELETE;
        $model->content = '<span class="is_del">内容已删除</span>';
        return $model->save();
        //return $model->updateAttributes(["status"=>self::STATUS_DELETE]);
        //return $model->delete();
    }

    /**
     * 获取用户评论过的文章
     * @param $user_id
     * @return array
     */
    public function getAidsByUid($user_id) {
        $aids = [];
        $result = static::find()->where(["user_id"=>$user_id,"status"=>self::STATUS_ENABLE])->all();
        if ($result) {
            foreach ($result as $item) {
                $aids[] = $this->findArtileId($item);
            }
        }
        return $aids;
    }

    /**
     * 返回文章id
     * @param $val
     * @return mixed
     */
    public function findArtileId($val) {
        if ($val["target_type"] == self::TYPE_ARTICLE) {
            return $val["target_id"];
        }
        $val = static::find($val["target_id"]);
        return $this->findArtileId($val);
    }

    /**
     * 获取用户评论文章的总数
     * @param $user_id
     * @return int
     * @throws \yii\mongodb\Exception
     */
    public static function getCommentTotal($user_id) {
        $data = (int)static::find()->where(["user_id"=>intval($user_id),"target_type"=>intval(self::TYPE_ARTICLE),"status"=>intval(self::STATUS_ENABLE)])->count();
        return $data;
    }

    /**
     * 获取用户评论文章和回复评论的总数
     * @param $user_id
     * @return int
     */
    public static function getCommentTotalNew($user_id) {
        $data = (int)static::find()->where(["user_id"=>intval($user_id),"status"=>intval(self::STATUS_ENABLE)])->andWhere(["in","target_type",[self::TYPE_ARTICLE,self::TYPE_COMMENT]])->count();
        return $data;
    }


    public static function getArticleByCommentId($comment_id) {
        $data = self::loadRowData($comment_id);
        if ($data['target_type'] == self::TYPE_COMMENT) {
            return self::getArticleByCommentId($data["target_id"]);
        }
        return ["id"=>$data["target_id"],"user_id"=>$data["user_id"],"text"=>Article::getFieldById($data['target_id'],"title"),"content"=>$data["content"]];
    }

    /**
     * 优质评论
     */
    public static function arrIndexQuality($page=1,$pageSize=5) {
        $key = "comment:quality:page:".$page;
        $data = [];//CommonUtil::getCache(__CLASS__,$key);
        if (!$data) {
            $q = static::find()->select(["target_id","user_id","content","created_at"])
                ->where(["status"=>self::STATUS_ENABLE,"target_type"=>self::TYPE_ARTICLE,"is_rec"=>self::REC_QUALITY])
                ->orderBy("updated_at DESC");
            $data = self::arrListByPage($q,$page,$pageSize);
            if (count($data["rows"])) {
                foreach ($data["rows"] as $k=> $row) {
                    unset($data["rows"][$k]["_id"]);
                    $data["rows"][$k]["title"] = Article::getFieldById($row["target_id"],"title");
                    $data["rows"][$k]["user_alias"] = User::getFieldById($row["user_id"]);
                    $data["rows"][$k]["user_image"] = User::getUserFace($row["user_id"]);
                    $data["rows"][$k]["created_at"] = date("Y-m-d",$row["created_at"]);
                    $data["rows"][$k]["user_url"] = CommonUtil::generateUrl($row['user_id'],Constant::ROUTE_USER);
                    $data["rows"][$k]["title_url"] = CommonUtil::generateUrl($row['target_id'],Constant::ROUTE_ARTICLE);
                }
                CommonUtil::setCache(__CLASS__,$key,$data);
            }
        }
        return $data;
    }

    public function getNotify() {
        return $this->hasMany(Notify::className(),['target'=>'_id']);
    }

    /**
     * 加载一条数据缓存
     * @param string $id
     * @return Notify|mixed|null
     */
    public static function loadRowById(string $id) {
        $key = "article:comment:id:".$id;
        $data = CommonUtil::getCache(__CLASS__,$key);
        if (!$data) {
            $data = static::find()->where(['_id'=>new ObjectId($id)])->asArray()->one();
            if ($data) {
                $data['_id'] = (string)$data['_id'];
                CommonUtil::setCache(__CLASS__,$key,$data,60);
            }
        }
        return $data;
    }

    /**
     * 是否含有子评论
     * @param $id
     * @return int
     */
    public static function isParentComment($id) {
        $key = "article:comment:isParent:id:".$id;
        $data = CommonUtil::getCache(__CLASS__,$key);
        if (!$data) {
            $data = static::find()->where(['target_id'=>$id])->count();
            $data = $data?:0;
            if ($data) {
                CommonUtil::setCache(__CLASS__,$key,$data);
            }
        }
        return $data;
    }

    /**
     * 获取所有文章标记的删除评论
     * @return array|\yii\mongodb\ActiveRecord
     */
    public static function getDelCommentAll() {
        $where = ['and'];
        $where[] = ['=','status',self::STATUS_DELETE];
        $data = static::find()->where($where)->asArray()->all();
        return $data;
    }

     public static function dataListTable($post){
         $q = static::find()->orderBy("created_at DESC");
         $data = self::arrListByPage($q,$post['page'],$post['pageSize']);
         if (count($data["rows"])) {
             foreach ($data["rows"] as $k => $v) {
                 $data["rows"][$k]["target_type"] = self::$typeArrayList[$v['type']];
                 $data["rows"][$k]["title"] = Article::getFieldById($v['article_id'],'title');
                 $data["rows"][$k]["created_at"] = date("Y-m-d H:i",$v["created_at"]);
                 $data["rows"][$k]["title_url"] =CommonUtil::generateUrl($v['article_id'],Constant::ROUTE_ARTICLE);
                 $data["rows"][$k]["reply_name"] = self::getAllCommentByTargetId($v['target_id'],$v['article_id'],$v['type']);
             }
         }
         return $data;
     }
    public static function getAllCommentByTargetId($target_id,$article_id,$type){
        $model = static::find()->where(['id'=>$target_id,"article_id"=>$article_id,'type'=>$type])->one();
        if ($model){
            return $model['nick_name'];
        }
    }
}
